/*
  "name": "大山后台管理系统",
  "version": "1.0",
  "description": "大山中后台管理系统",
  "author": "大山",
  "date": "2023-04-04",
  "license": "MIT",
*/

const bodyParser = require('body-parser');
const jsonParser = bodyParser.json({ limit: '1000mb' });
const resbody = require('../utils/resbody');
const utils = require('../utils/utils');
const token = require('../utils/token');
const connection = require('../utils/sql');
const mysql = require('mysql');
const escape = mysql.escape;
const jwt = require("jsonwebtoken");
const { log } = require('debug/src/node');

module.exports = (app) => {
	
	// 验证token
	const whiteList = ['/api/login'];
	let userTokenData;
	
	app.use((req,res,next) => {
		if(!whiteList.includes(req.url)) {
			token.verifyToken(req.headers.authorization).then(res => {
				userTokenData = res
				next()
			}).catch(e => {
				// token过期时的err值："message": "jwt expired",
				// token无效时的err值："message": "jwt malformed | invalid token | invalid signature",
				// 没有token的err值："message": "jwt must be provided"
				let msg = token.tokenMsg().find(item => item.type === e.message)['msg']
				// res.status(200).send(res.json(resbody.getFailResult({}, msg)))
				res.json(resbody.getFailResult({}, msg, 401))
			})
		} else {
			next()
		}
	})
	
	// 登录日志 - 查询数组
	app.get('/api/loginInfo', (req,res) => {
		let sort = 'desc'; // 排序
		const { pageNum, pageSize, name, loginName } = req.query;
		// 分页
		let num = pageNum ? parseInt(pageNum) - 1 : 0;
		let size = pageSize ? parseInt(pageSize) : 10;
		let skip =  num * size;
		let limit = skip + ',' + size;
		// 模糊查询：
		let fuzzyQuery = '';
		let queryArray = [];
		
		if (name) {
			let queryVal = `name like '%${name}%'`;
			queryArray.push(queryVal);
		}
		if (loginName) {
			let queryVal = `loginName like '%${loginName}%'`;
			queryArray.push(queryVal)
		}
		if (queryArray.length === 1) {
			fuzzyQuery = ` where ${queryArray.join(',')} and isDelete<>'0'`
		} else if (queryArray.length === 0) {
			fuzzyQuery = ` where isDelete<>'0'`
		} else {
			fuzzyQuery = ` where ${queryArray.join(',').replace(',', ' and ')} and isDelete<>'0'`
		}
		
	    const sql = `SELECT SQL_CALC_FOUND_ROWS id, loginName, name, ipAddress, os, browser, loginTime FROM loginInfo${fuzzyQuery} order by loginTime ${sort} limit ${limit};`;
		const sqlTotal = `SELECT COUNT(id) as total FROM loginInfo${fuzzyQuery};`;
		
		connection(sql, (error, result, fileds) => {
	        if(error) {
	            res.json(resbody.getFailResult(error))
	        }else{
				result.forEach(item => {
					item.loginTime = utils.parseTime(item.loginTime)
				})
	            // 返回
				utils.getTableTotal(connection, sqlTotal).then(total => {
					console.log(total)
					const returnNum = num+1;
					const returnData = {
						total: total,
						rows: result,
						pageNum: returnNum,
						pageSize: size
					}
					res.json(resbody.getSuccessResult(returnData))
				}).catch(err => {
					
				})
	        }
	    })
	})
	
	// 登录日志 - 清空（物理清空）
	app.delete('/api/loginInfo/clean',(req,res) => {
		utils.recordOperaLog(connection, '清空登录日志', userTokenData)
	    const sql = `UPDATE loginInfo SET isDelete = '0'`
	    connection(sql,(error, result, fileds) => {
	        if(error){
	            console.log(error)
	            res.json(resbody.getFailResult(error))
	        }else{
	            res.json(resbody.getSuccessResult({}, '清空成功！'))
	        }
	    })
	})
}
